from django.shortcuts import render
from rest_framework.views import APIView
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView

# Create your views here.
from goods.models import SKU
from orders.serializers import OrderSerializers, SaveOrderSerializers
from decimal import Decimal


class OrdersView(APIView):

    def get(self,request):
        # 获取用户对象
        user=request.user
        # 获取缓存数据  获取选中状态的sku_id
        # 建立缓存连接
        conn=get_redis_connection('cart')
        # 获取商品数量  sku_id count
        sku_count=conn.hgetall('cart_%s'%user.id)

        cart={}
        for sku_id,count in sku_count.items():
            cart[int(sku_id)]=int(count)

        # 获取选中状态的sku_id
        sku_ids=conn.smembers('cart_selecte_%s'%user.id)

        # 根据缓存中给存储的sku_id查询商品对象
        skus=SKU.objects.filter(id__in=sku_ids)

        # 商品对象添加count
        for sku in skus:
            sku.count=cart[sku.id]

        # 运费
        freight=Decimal('10.00')
        # 序列化返回
        ser=OrderSerializers({'skus':skus,'freight':freight})

        return Response(ser.data)

class SaveOrderView(CreateAPIView):

    serializer_class = SaveOrderSerializers

